package io.github.wppli.infrastructure.persistent.repository;

import io.github.wppli.domain.recommond.model.entity.UserBehaviorEntity;
import io.github.wppli.domain.recommond.repository.IUserBehaviorRepository;
import io.github.wppli.infrastructure.persistent.dao.IUserBehaviorsDao;
import io.github.wppli.infrastructure.persistent.po.UserBehaviors;
import lombok.AllArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * @author li--jiaqiang 2025−03−12
 */
@Repository
@AllArgsConstructor
public class UserBehaviorRepository implements IUserBehaviorRepository {

    private final IUserBehaviorsDao userBehaviorsDao;

    @Override
    public List<UserBehaviorEntity> queryByUserId(Long userId) {
        List<UserBehaviors> userBehaviors = userBehaviorsDao.queryByUserId(userId);
        return getUserBehaviorEntities(userBehaviors);
    }


    @Override
    public List<UserBehaviorEntity> findAll() {
        List<UserBehaviors> userBehaviors = userBehaviorsDao.findAll();
        return getUserBehaviorEntities(userBehaviors);
    }

    @Override
    public List<UserBehaviorEntity> findAllWithPagination(int batchSize, int offset) {
        List<UserBehaviors> userBehaviors = userBehaviorsDao.findAllWithPagination(batchSize, offset);
        return getUserBehaviorEntities(userBehaviors);
    }

    @Override
    public void save(UserBehaviorEntity userBehaviorEntity) {
        UserBehaviors userBehaviors = new UserBehaviors();
        userBehaviors.setId(userBehaviorEntity.getId());
        userBehaviors.setUserId(userBehaviorEntity.getUserId());
        userBehaviors.setProductId(userBehaviorEntity.getProductId());
        userBehaviors.setBehaviorType(userBehaviorEntity.getUserBehaviorType());
        userBehaviors.setBehaviorScore(userBehaviorEntity.getUserBehaviorScore());
        userBehaviors.setCreateTime(LocalDateTime.now());

        userBehaviorsDao.insert(userBehaviors);
    }

    @NotNull
    private List<UserBehaviorEntity> getUserBehaviorEntities(List<UserBehaviors> userBehaviors) {
        if (userBehaviors.isEmpty()) {
            return Collections.emptyList();
        }
        List<UserBehaviorEntity> userBehaviorEntityList = new LinkedList<>();
        for (UserBehaviors userBehavior : userBehaviors) {
            UserBehaviorEntity userBehaviorEntity = UserBehaviorEntity.builder()
                    .id(userBehavior.getId())
                    .userId(userBehavior.getUserId())
                    .productId(userBehavior.getProductId())
                    .userBehaviorType(userBehavior.getBehaviorType())
                    .build();
            userBehaviorEntityList.add(userBehaviorEntity);
        }
        return userBehaviorEntityList;
    }
}